package com.wang.controller;

import com.wang.pojo.Book;
import com.wang.service.BookService;
import com.wang.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookServiceImpl bookServiceimpl;

    @GetMapping("/findAllBook")
    public String findAllBook(HttpServletRequest request){
        List<Book> books = bookServiceimpl.findAllBook();
        request.setAttribute("books", books);
        return "/listBook";
    }

    @GetMapping("/addBook")
    public String addBook(Book book){
        int i = bookServiceimpl.addBook(book);
        return "forward:/findAllBook";
    }

    @GetMapping("/turnAddBook")
    public String turnAddBook(){
        return "addBook";
    }

    @GetMapping("/findBookById/{id}")
    public String findBookById(@PathVariable("id") int id, Model model){
        Book book = bookServiceimpl.findBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    @GetMapping("/updateBook")
    public String updateBook(Book book){
        int i = bookServiceimpl.updateBook(book);
        return "forward:/findAllBook";
    }

    @GetMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id") int id){
        bookServiceimpl.deleteBookById(id);
        return "forward:/findAllBook";
    }

}
